﻿using System;
using System.Collections.Generic;
using System.Data.Linq;
using System.Linq;
using System.Transactions;
using BSU.GraduateWork.Data.Model;
using BSU.GraduateWork.Data.Repositories.Interfaces;

namespace BSU.GraduateWork.Data.Repositories
{
    public class Problem2DRepository : BaseRepository<Problem2D, int>, IProblem2DRepository
    {
        public override Problem2D Get(int id)
        {
            var problem = base.Get(id);

            var pointRepository = new Point2DRepository();
            problem.Solution.U = pointRepository.List(problem.SolutionId);

            problem.ExactSolution.U = pointRepository.List(problem.ExactSolutionId);

            return problem;
        }

        public override Problem2D Save(Problem2D entity)
        {
            using (var ts = new TransactionScope())
            {
                var context = GetNewContext();
                entity = base.Save(entity, context);

                var pointRepository = new Point2DRepository();

                var solutionPoints = entity.Solution.U.Select(point => new SolutionPoint2D
                                                                           {
                                                                               X = point.X, Y = point.Y, U = point.Z, IsBoundary = point.IsBoundary, SolutionId = entity.SolutionId
                                                                           }).ToList();
                pointRepository.SaveAll(solutionPoints);

                if (entity.ExactSolution != null && entity.ExactSolution.U != null)
                {
                    var exactSolutionPoints = entity.ExactSolution.U.Select(point => new SolutionPoint2D
                            {
                                X = point.X,
                                Y = point.Y,
                                U = point.Z,
                                IsBoundary = point.IsBoundary,
                                SolutionId = entity.ExactSolutionId
                            }).ToList();

                    pointRepository.SaveAll(exactSolutionPoints);
                }

                ts.Complete();
            }
            return entity;
        }

        public List<Problem2D> List()
        {
            var context = GetNewContext();
            var table = context.GetTable<Problem2D>();

            return table.ToList();
        }
    }
}